package com.sxyc.tintin.sdk;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.kit.ParaMap;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.jfinal.weixin.sdk.utils.RetryUtils;


public class SnsAccessTokenApi {

	private static String AMI = "http://wechat.ami-tek.com.cn/e00c373bd430/application/wx/oauth2.php";
    private static String url = "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code";
    private static String authorize_uri = "https://open.weixin.qq.com/connect/oauth2/authorize";
    private static String qrconnect_url = "https://open.weixin.qq.com/connect/qrconnect";

    /**
     * 生成Authorize链接
     * @param redirect_uri 回跳地址
     * @param snsapiBase snsapi_base（不弹出授权页面，只能拿到用户openid）snsapi_userinfo（弹出授权页面，这个可以通过 openid 拿到昵称、性别、所在地）
     * @return url
     */
  	public static String getAuthorizeURL(String redirect_uri, boolean snsapiBase) {
  		return getAuthorizeURL(redirect_uri, null, snsapiBase);
  	}
  	
  	/**
     * 生成Authorize链接
     * @param redirect_uri 回跳地址
     * @param state 重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
     * @param snsapiBase snsapi_base（不弹出授权页面，只能拿到用户openid）snsapi_userinfo（弹出授权页面，这个可以通过 openid 拿到昵称、性别、所在地）
     * @return url
     */
  	public static String getAuthorizeURL(String redirect_uri, String state, boolean snsapiBase) {
  		String authorize_uri = AMI;
  		Map<String, String> params = new HashMap<String, String>();
  		params.put("appId", PropKit.get("appId"));
  		params.put("response_type", "code");
  		params.put("redirect_uri", redirect_uri);
  		// snsapi_base（不弹出授权页面，只能拿到用户openid）
  		// snsapi_userinfo（弹出授权页面，这个可以通过 openid 拿到昵称、性别、所在地）
  		if (snsapiBase) {
  			params.put("scope", "snsapi_base");
  		} else {
  			params.put("scope", "snsapi_userinfo");
  		}
  		if (StrKit.isBlank(state)) {
  			params.put("state", "");
  		} else {
  			params.put("state", state);
  		}
  		String para = PaymentKit.packageSign(params, false);
  		authorize_uri = authorize_uri + "?" + para;
//  		System.out.println("authorize_uri = "+authorize_uri);
  		return authorize_uri;
  	}
  	
  	public static String getYCOpenid(String redirect_uri) {
		String authorize_uri = "http://www.yctms.com/WeiXin/AuthorizeTest";
		Map<String, String> params = new HashMap<String, String>();
		params.put("appid", "wx473eda9a3e0d8207");
		params.put("response_type", "code");
		params.put("redirect_uri", redirect_uri);
		params.put("scope", "snsapi_base");
		params.put("state", "wx#wechat_redirect");
		String para = PaymentKit.packageSign(params, false);
		authorize_uri = authorize_uri + "?" + para;
//		System.out.println("authorize_uri = "+authorize_uri);
		return authorize_uri;
	}
  	
    /**
     * 生成Authorize链接
     * @param appId 应用id
     * @param redirectUri 回跳地址
     * @param state 重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
     * @param snsapiBase snsapi_base（不弹出授权页面，只能拿到用户openid）snsapi_userinfo（弹出授权页面，这个可以通过 openid 拿到昵称、性别、所在地）
     * @return url
     */
    public static String getAuthorizeURL(String appId, String redirectUri, String state, boolean snsapiBase) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", appId);
        params.put("response_type", "code");
        params.put("redirect_uri", redirectUri);
        // snsapi_base（不弹出授权页面，只能拿到用户openid）
        // snsapi_userinfo（弹出授权页面，这个可以通过 openid 拿到昵称、性别、所在地）
        if (snsapiBase) {
            params.put("scope", "snsapi_base");
        } else {
            params.put("scope", "snsapi_userinfo");
        }
        if (StrKit.isBlank(state)) {
            params.put("state", "wx#wechat_redirect");
        } else {
            params.put("state", state.concat("#wechat_redirect"));
        }
        String para = PaymentKit.packageSign(params, false);
        return authorize_uri + "?" + para;
    }


    /**
     * 生成网页二维码授权链接
     * @param appId 应用id
     * @param redirect_uri 回跳地址
     * @return url
     */
    public static String getQrConnectURL(String appId, String redirect_uri) {
        return getQrConnectURL(appId, redirect_uri, null);
    }

    /**
     * 生成网页二维码授权链接
     * @param appId 应用id
     * @param redirect_uri 回跳地址
     * @param state 重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
     * @return url
     */
    public static String getQrConnectURL(String appId, String redirect_uri, String state) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", appId);
        params.put("response_type", "code");
        params.put("redirect_uri", redirect_uri);
        params.put("scope", "snsapi_login");
        if (StrKit.isBlank(state)) {
            params.put("state", "wx#wechat_redirect");
        } else {
            params.put("state", state.concat("#wechat_redirect"));
        }
        String para = PaymentKit.packageSign(params, false);
        return qrconnect_url + "?" + para;
    }

    /**
     * 通过code获取access_token
     *
     * @param code   第一步获取的code参数
     * @param appId  应用唯一标识
     * @param secret 应用密钥AppSecret
     * @return SnsAccessToken
     */
    public static SnsAccessToken getSnsAccessToken(String appId, String secret, String code)
    {
    	String res = CacheKit.get("code", code);
		if (res == null) {
			CacheKit.put("code", code, "1");
		}else{
			LogKit.warn("code 去重！");
			return null;
		}
        final Map<String, String> queryParas = ParaMap.create("appid", appId).put("secret", secret).put("code", code).getData();

        return RetryUtils.retryOnException(3, new Callable<SnsAccessToken>() {

            @Override
            public SnsAccessToken call() throws Exception {
                String json = HttpUtils.get(url, queryParas);
                return new SnsAccessToken(json);
            }
        });
    }
    
    //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code 
    public static String getAccesstoken(String code){
    	String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx473eda9a3e0d8207&secret=2651ffab42eef1acbcd85d07b1e22315&code="+code+"&grant_type=authorization_code";
    	String json = HttpUtils.get(url);
    	System.out.println(json);
    	JSONObject res = JSONObject.parseObject(json);
    	return res.getString("openid");
    }
}
